<?php

namespace app\wx\validate;

use think\Validate;
use think\Db;

class DepartmentValidate extends Validate
{
    protected $rule =   [
        'id' => [
            'require'
        ],
        'name' => [
            'require',
            'max' => 32,
            'checkName' => 'name'
        ],
        'name_en' => [
            'max' => 32,
            'checkName' => 'name_en'
        ],
        'parentid' => [
            'require',
            'integer'
        ],
        'order' => [
            'integer'
        ],
    ];
    
    protected $message  =   [
        'id.require'       => 'ID不能为空',
        'name.require'     => '名称必须',
        'name.max'         => '名称长度最大32个字符',
        'name_en.require'  => '名称必须',
        'name_en.max'      => '名称长度最大32个字符',
        'parentid.require' => '父部门ID不能为空',
        'parentid.integer' => '父部门ID只能为整型',
        'order.integer'    => '排序只能为整型',
    ];

    protected $scene = [
        'add' => ['name','name_en','parentid','order'],
        'edit' => ['id','name','name_en','parentid','order']
    ];

    //同一个层级的部门名称不能重复,以及字符不能包括\:?”<>｜
    protected function checkName($value,$rule,$data=[])
    {
        $pattern = '/^[\\\:\?”\<\>\｜]+/';
        if(preg_match($pattern,$value)) return '字符不能包括\:?”<>｜';
        $think_type = $data['think_type'] ?? 'add';
        if($think_type == 'edit'){
            //有就是修改，不包含自己
            $id = $data['id'];
            $result = Db::name('department')
            ->where('parentid',$data['parentid'])
            ->where($rule,$value)
            ->where('id','<>',$id)
            ->field('id')
            ->find();
        }else{
            $result = Db::name('department')
            ->where('parentid',$data['parentid'])
            ->where($rule,$value)
            ->field('id')
            ->find();
        }
        if($result) return '同一个层级的部门名称不能重复';
        return true;
    }

}


